<?php
namespace App\Services\Company\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class CompanyCategory extends Model
{
    use HasFactory;

    protected $table = 'shop_category';

    protected $fillable = [
        'name', 'parent_id', 'parent_chain', 'user_id','company_id','workplace_id'
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $parent = $model->parent;
            if ($parent) {
                $model->parent_chain = $parent->parent_chain
                    ? $parent->parent_chain . ',' . $parent->id // 如果parent有parent_chain，则将当前id添加到其后面
                    : $parent->id; // 如果parent没有parent_chain，则将当前id设置为第一个
            }
        });
    }

    public function parent()
    {
        return $this->belongsTo(CompanyCategory::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(__CLASS__, 'parent_id');
    }
}
